package com.yiyiooo.Abp.basics;

import com.yiyiooo.Abp.AppBootstrap;
import com.yiyiooo.client.api.SessionApi;
import com.yiyiooo.client.invoker.ApiException;
import com.yiyiooo.client.invoker.Configuration;
import com.yiyiooo.client.model.AbpUserConfigurationDto;
import com.yiyiooo.client.model.AuthenticateResultModel;
import com.yiyiooo.client.model.GetCurrentLoginInformationsOutput;
import com.yiyiooo.client.model.TenantLoginInfoDto;
import com.yiyiooo.client.model.UserLoginInfoDto;

public class AbpSession {
    private long userId = 0;
    private UserLoginInfoDto user =null;
    private int tenantId = 0;
    private TenantLoginInfoDto tenant=null;
    private String accessToken = "";
    private String encryptedAccessToken = "";
    private AbpUserConfigurationDto userConfig = new AbpUserConfigurationDto();

    private static AbpSession instance = new AbpSession();

    public static AbpSession getInstance() {
        return instance;
    }
    private AbpSession(){
        accessToken =AppBootstrap.localStore.getStore("accessToken");
        encryptedAccessToken =AppBootstrap.localStore.getStore("encryptedAccessToken");
        String tid = AppBootstrap.localStore.getStore("Abp.tenantId");
        tenantId = Integer.parseInt(tid==null||tid.equals("")?"0":tid);
        initUserConfig();
        getCurrentLoginInfo();
    }

    public void login(AuthenticateResultModel model){
        accessToken = model.getAccessToken();
        encryptedAccessToken=model.getEncryptedAccessToken();
        AppBootstrap.localStore.setStore("accessToken",accessToken);
        AppBootstrap.localStore.setStore("encryptedAccessToken",encryptedAccessToken);
        initUserConfig();
        getCurrentLoginInfo();
    }
    public void logout(){
        accessToken = "";
        encryptedAccessToken = "";
        AppBootstrap.localStore.setStore("accessToken",accessToken);
        AppBootstrap.localStore.setStore("encryptedAccessToken",encryptedAccessToken);
    }

    // 获取 accessToken
    public String getAccessToken(){
        return accessToken;
    }

    // 获取 encryptedAccessToken
    public String getAncryptedAccessToken(){ return encryptedAccessToken;    }

    public AbpUserConfigurationDto  getConfig(){
        return  userConfig;
    }

    public void savePassword(String password){
        LocalStore.getInstance().setStore("password",password);
    }
    public String getPassword(){
        return LocalStore.getInstance().getStore("password");
    }
    // 获取 userId
    public Long getUserid(){
        return userId;
    }

    public UserLoginInfoDto getUser(){return  user==null?new UserLoginInfoDto():user;}
    // 获取 tenantId
    public String getTenantId(){
        return tenantId==0?"":tenantId+"";
    }
    public TenantLoginInfoDto getTenant(){return tenant==null?new TenantLoginInfoDto():tenant;}
    // 判断权限
    public Boolean isGuard(String args[]){
        for(String item : args){
            if( userConfig.getAuth().getAllPermissions().get(item)==null || userConfig.getAuth().getAllPermissions().get(item)=="false")
                return false;
        }
        return true;
    }

    public void setTenantId(int tenantId) {
        this.tenantId = tenantId;
        AppBootstrap.localStore.setStore("Abp.tenantId",tenantId+"");
    }

    public void initUserConfig(){
        try{
            new SessionApi().apiServicesAppSessionGetUserConfigurationsGetAsync(new AbpApiCallback<AbpUserConfigurationDto>() {
                @Override
                public void call(HttpClientResult<AbpUserConfigurationDto> callData) {
                    if(!callData.success) return;
                    userConfig = callData.result;
                }
            });
        }
        catch (ApiException ex){
            AppMessage.Err(ex.getMessage());
        }catch (Exception ex){
            AppMessage.Err("非api异常"+ex.getMessage(),"apiServicesAppSessionGetUserConfigurationsGetAsync");
        }
    }
    public void getCurrentLoginInfo(){
        try{
            new SessionApi().apiServicesAppSessionGetCurrentLoginInformationsGetAsync(new AbpApiCallback<GetCurrentLoginInformationsOutput>() {
                @Override
                public void call(HttpClientResult<GetCurrentLoginInformationsOutput> callData) {
                    if(!callData.success) return;
                    user = callData.result.getUser();
                    if(user!=null) userId=user.getId();
                    tenant = callData.result.getTenant();
                    if(tenant!=null) setTenantId(tenant.getId());
                }
            });
        }
        catch (ApiException ex){
            AppMessage.Err(ex.getMessage(),"apiServicesAppSessionGetCurrentLoginInformationsGetAsync");
        }catch (Exception ex){
            AppMessage.Err("非api异常"+ex.getMessage(),"apiServicesAppSessionGetCurrentLoginInformationsGetAsync");
        }
    }

}
